package com.hskn.hss.module.rptEmployeeWork.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.empPlan.entity.EmpPlan;
import com.hskn.hss.module.empPlan.service.EmpPlanService;
import com.hskn.hss.module.empPlanDate.entity.EmpPlanDate;
import com.hskn.hss.module.empPlanDate.service.EmpPlanDateService;
import com.hskn.hss.module.empPlanEmployee.entity.EmpPlanEmployee;
import com.hskn.hss.module.empPlanEmployee.service.EmpPlanEmployeeService;
import com.hskn.hss.module.grid.entity.Grid;
import com.hskn.hss.module.grid.service.IGridService;
import com.hskn.hss.module.rptEmployeeWork.entity.RptEmployeeWork;
import com.hskn.hss.module.rptEmployeeWork.service.RptEmployeeWorkService;
import com.hskn.hss.module.rptEmployeeWork.to.InitRptEmployeeWorkTO;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.workgroup.entity.WorkGroup;
import com.hskn.hss.module.workgroup.service.IWorkGroupService;
import com.hskn.hss.module.workkaoqin.entity.WorkKaoqin;
import com.hskn.hss.module.workkaoqin.mapper.WorkKaoqinMapper;
import com.hskn.hss.module.workkaoqin.service.IWorkKaoqinService;
import com.hskn.hss.module.workrule.entity.WorkRule;
import com.hskn.hss.module.workrule.service.IWorkRuleService;
import com.hskn.hss.utils.DateUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Slf4j
@RestController
@RequestMapping("/hss/rptEmployeeWork")
public class RptEmployeeWorkController {

    @Autowired
    private RptEmployeeWorkService rptEmployeeWorkMapper;
    @Autowired
    private RptEmployeeWorkService rptEmployeeWorkService;
    @Autowired
    private EmpPlanDateService empPlanDateService;
    @Autowired
    private EmpPlanService empPlanService;
    @Autowired
    private EmpPlanEmployeeService empPlanEmployeeService;
    @Autowired
    private ITlEmployeeService employeeService;
    @Autowired
    private IGridService gridService;
    @Autowired
    private IWorkRuleService workRuleService;
    @Autowired
    private IWorkGroupService workGroupService;
    @Autowired
    private IWorkKaoqinService workKaoqinService;
    @Autowired
    private WorkKaoqinMapper workKaoqinMapper;

    @RequestMapping(value = "list", method = RequestMethod.POST)
    public AjaxResult<Object> list(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = rptEmployeeWorkMapper.mList(params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "getRptEmployeeWorkList", method = RequestMethod.POST)
    public AjaxResult<Object> getRptEmployeeWorkList() {
        try {
            return AjaxResult.success(rptEmployeeWorkService.getRptEmployeeWorkList());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "InitRptEmployeeWorkByDate", method = RequestMethod.POST)
    public AjaxResult<Object> InitRptEmployeeWorkByDate(@RequestBody @Validated InitRptEmployeeWorkTO initRptEmployeeWorkTO) {
        Date date = initRptEmployeeWorkTO.getDate();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String calendarDate = sdf1.format(date);
        List<RptEmployeeWork> rptEmployeeWorkList1 = rptEmployeeWorkService.list(new QueryWrapper<RptEmployeeWork>().lambda().eq(RptEmployeeWork::getWorkDate,calendarDate));
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(rptEmployeeWorkList1)){
            rptEmployeeWorkService.removeByIds(rptEmployeeWorkList1.stream().map(RptEmployeeWork::getId).collect(Collectors.toList()));
        }
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
        String calendarMonth = sdf2.format(date);

        QueryWrapper<EmpPlanDate> empPlanDateQueryWrapper = new QueryWrapper<>();
        empPlanDateQueryWrapper.lambda().ge(EmpPlanDate::getEndDate, calendarDate);
        empPlanDateQueryWrapper.lambda().le(EmpPlanDate::getStartDate, calendarDate);
        List<EmpPlanDate> empPlanDateList = empPlanDateService.list(empPlanDateQueryWrapper);

        List<EmpPlan> empPlanList = empPlanService.list(new QueryWrapper<>());
        Map<String, EmpPlan> empPlanMap = empPlanList.stream().collect(Collectors.groupingBy(EmpPlan::getId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));


        List<EmpPlanEmployee> empPlanEmployeeList = empPlanEmployeeService.list(new QueryWrapper<>());
        Map<String, List<EmpPlanEmployee>> empPlanEmployeeMap = empPlanEmployeeList.stream().collect(Collectors.groupingBy(EmpPlanEmployee::getPlanId));

        List<TlEmployee> tlEmployeeListOne = employeeService.list(new QueryWrapper<>());
        Map<String, TlEmployee> tlEmployeeMap = tlEmployeeListOne.stream().collect(Collectors.groupingBy(TlEmployee::getId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));


        List<WorkGroup> workGroupList = workGroupService.list(new QueryWrapper<>());
        Map<String, WorkGroup> workGroupMap = workGroupList.stream().collect(Collectors.groupingBy(WorkGroup::getWorkGroupId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));

        List<Grid> gridList = gridService.list(new QueryWrapper<Grid>().lambda().eq(Grid::getGridType, 0));
        Map<String, Grid> gridMap = gridList.stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));

        List<WorkRule> workRuleList = workRuleService.list(new QueryWrapper<>());
        Map<String, WorkRule> workRuleMap = workRuleList.stream().collect(Collectors.groupingBy(WorkRule::getWorkRuleId, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0))));

        for (EmpPlanDate empPlanDate : empPlanDateList) {

            List<EmpPlanEmployee> empPlanEmployeeList1 = empPlanEmployeeMap.get(empPlanDate.getPlanId());
            if (null != empPlanEmployeeList1) {
                for (EmpPlanEmployee empPlanEmployee : empPlanEmployeeList1) {
                    WorkGroup workGroup = workGroupMap.get(empPlanDate.getWorkGroupId());
                    if (null != workGroup) {
                        //勤类型，固定班1，冬夏班2
                        Integer kaoqinType = workGroup.getKaoqinType();
                        //1:夏季,2:冬季
                        String season = DateUtils.getCurrentSeason(new Date());
                        String kaoqinIds = workGroup.getKaoqinIds();
                        if (StringUtils.isEmpty(kaoqinIds)) {
                            return AjaxResult.fail("考勤段为空");
                        }
                        List<WorkKaoqin> workKaoqinList = workKaoqinMapper.selectBatchIds(Arrays.asList(kaoqinIds.split(",")));
                        for (WorkKaoqin workKaoqin : workKaoqinList) {

//                                String workDate = DateUtil.format(new Date(), "yyyy-MM-dd");
                            //重复判断
                            QueryWrapper<RptEmployeeWork> rptEmployeeWrokWrapper = new QueryWrapper<>();
                            rptEmployeeWrokWrapper.lambda().eq(RptEmployeeWork::getEmployeeId, empPlanEmployee.getEmployeeId());
                            rptEmployeeWrokWrapper.lambda().eq(RptEmployeeWork::getPlanId, empPlanEmployee.getPlanId());
                            rptEmployeeWrokWrapper.lambda().eq(RptEmployeeWork::getWorkDate, calendarDate);
                            rptEmployeeWrokWrapper.lambda().eq(RptEmployeeWork::getShiftId, workKaoqin.getWorkKaoqinId());
                            List<RptEmployeeWork> rptEmployeeWorkList = rptEmployeeWorkService.list(rptEmployeeWrokWrapper);
                            if (!CollectionUtils.isEmpty(rptEmployeeWorkList)) {
                                continue;
                            }
                            String planStartTime = null;//排班开始时间
                            String planEndTime = null;//排班结束时间
                            if (1 == kaoqinType) {//固定班
                                planStartTime = workKaoqin.getSbsj();
                                planEndTime = workKaoqin.getXbsj();
                            } else if (2 == kaoqinType) {//冬夏班
                                if ("summer".equals(season)) {
                                    planStartTime = workKaoqin.getXsbsj();
                                    planEndTime = workKaoqin.getXxbsj();
                                } else if ("winter".equals(season)) {
                                    planStartTime = workKaoqin.getDsbsj();
                                    planEndTime = workKaoqin.getDxbsj();
                                }
                            }
                            RptEmployeeWork rptEmployeeWork = new RptEmployeeWork();
                            rptEmployeeWork.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                            rptEmployeeWork.setEmployeeId(empPlanEmployee.getEmployeeId());
                            TlEmployee tlEmployee = tlEmployeeMap.get(empPlanEmployee.getEmployeeId());
                            if (null != tlEmployee) {
                                tlEmployee.setShiftStatus(0);
                                employeeService.updateById(tlEmployee);

                                rptEmployeeWork.setEmployeeName(tlEmployee.getName());
                            }
                            EmpPlan empPlan = empPlanMap.get(empPlanDate.getPlanId());
                            if (null != empPlan) {
                                rptEmployeeWork.setPlanId(empPlan.getId());
                                rptEmployeeWork.setPlanName(empPlan.getPlanName());
                                rptEmployeeWork.setGridId(empPlan.getGridId());
                                rptEmployeeWork.setDepId(empPlan.getDepartmentId());
                                Grid grid = gridMap.get(empPlan.getGridId());
                                if (null != grid) {
                                    rptEmployeeWork.setGridName(grid.getName());
                                    if (null != grid.getKm()) {
                                        rptEmployeeWork.setAllProgress(grid.getKm().intValue());
                                    }
                                }
                                WorkRule workRule = workRuleMap.get(empPlan.getWorkRuleId());
                                if (null != workRule) {
                                    rptEmployeeWork.setRuleId(workRule.getWorkRuleId());
                                    rptEmployeeWork.setRuleName(null == workRule.getRuleName() ? "" : workRule.getRuleName());
                                }
                            }
                            rptEmployeeWork.setGroupId(workGroup.getWorkGroupId());
                            rptEmployeeWork.setGroupName(workGroup.getName());
                            rptEmployeeWork.setWorkDate(calendarDate);
                            rptEmployeeWork.setWorkMonth(calendarMonth);
                            rptEmployeeWork.setPlanStartTime(DateUtil.parse(calendarDate + planStartTime, "yyyy-MM-ddHH:mm"));
                            rptEmployeeWork.setPlanEndTime(DateUtil.parse(calendarDate + planEndTime, "yyyy-MM-ddHH:mm"));
                            rptEmployeeWork.setCreateTime(new Date());
                            rptEmployeeWork.setShiftId(workKaoqin.getWorkKaoqinId());
                            rptEmployeeWork.setShiftName(workKaoqin.getName());
                            rptEmployeeWorkService.save(rptEmployeeWork);
                        }
                    }

                }
            }

        }
        return AjaxResult.success();
    }


}

